package com.cimstech.websocketservlet;

import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.cimstech.connect.Connect;
import com.cimstech.model.Values;

/**
 * WebSocket服务类
 *
 * @author dyzhu
 */
@ServerEndpoint(value = "/Report")
public class SocketServer {
    private static Session session;

    @OnOpen
    public void onOpen(Session session) {
        SocketServer.session = session;
        System.out.println("建立连接");
        System.out.println("注入服务");
        Connect.setSocketServer(this);
    }

    @OnClose
    public void onClose() {
        System.out.println("连接断开");
        Connect.removeSocketServer(this);
    }

    /**
     * 收到消息事件
     *
     * @param message
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String message) throws IOException {
        System.out.print("收到数据：" + message);
    }

    ;

    /**
     * 发生错误处理
     *
     * @param throwable
     */
    @OnError
    public void onError(Throwable throwable) {
    }

    /**
     * 报告推送
     *
     * @param type   报告的设备IP
     * @param values 报告内容
     */
    public void update(String type, Values values) {
        // 拼JSON
        StringBuffer sb = new StringBuffer();
        sb.append("{\"ip\":\"").append(type).append("\",\"type\":\"").append("update").append("\",\"update\":").append(values.toString()).append("}");
//        System.out.println(sb.toString());
        try {
            session.getBasicRemote().sendText(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 触发事件推送(设备断开/链接通知)
     *
     * @param type  通知的设备的IP
     * @param event 通知事件内容
     */
    public void event(String type, String event) {
        // 拼JSON
        StringBuffer sb = new StringBuffer();
        sb.append("{\"ip\":\"").append(type).append("\",\"type\":\"").append("event").append("\",\"event\":\"").append(event).append("\"}");
        try {
            session.getBasicRemote().sendText(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}